package com.lam.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.base.domain.tree.TreeNode;
import com.lam.common.base.domain.tree.TreeUtil;
import com.lam.common.base.page.TableData;
import com.lam.common.components.dict.DictUtil;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.components.easyexcel.export.DownloadUtil;
import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.SystemConstant;
import com.lam.common.utils.JsonUtil;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.system.entity.SysMenu;
import com.lam.system.param.SysMenuParam;
import com.lam.system.service.SysMenuService;
import com.lam.system.util.MenuUtil;

/**
 * 菜单管理Controller
 * 
 * @author admin
 * @date 2022-09-01
 */
@Log(title = "菜单管理")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/sys/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询菜单管理列表
     */
    @Log(oper="列表查询")
//    @DictAutoTransfer(deep = true)
    @PreAuthorize("@ss.hasPm('sys:menu:list')")
    @GetMapping("/list")
    public Result list(SysMenuParam param) {
    
    	PageHelper.orderBy("parent_id,sort_no");
        List<SysMenu> list = sysMenuService.selectList(param);
        DictUtil.convertJavaList(list);
        list = TreeUtil.buildTree(list, MenuUtil.MENU_TOP_ID);
        return Result.ok(new TableData(list, list.size()));
    }
    
    /**
     * 查询菜单管理列表
     */
    @Log(oper="后端菜单列表")
    @PreAuthorize("@ss.hasPm('sys:menu:list')")
    @GetMapping("/enableList")
    public Result enableList(SysMenuParam param) {
    
    	param.setStatus(CommonConstant.STATUS_NORMAL);
    	PageHelper.orderBy("parent_id,sort_no");
        List<SysMenu> list = sysMenuService.selectList(param);
        
		List<TreeNode> treeNodeList = JsonUtil.toJavaList(list, TreeNode.class, "id", "parentId", "name=>title", "icon", "menuType=>type", "sortNo");
        if(param.isUseSelectAll()) {
        	Map<String, Object> json = new HashMap<>();
            json.put("treeData", TreeUtil.buildTree(treeNodeList, MenuUtil.MENU_TOP_ID));
        	json.put("allIdList", list.stream().map(t->t.getId()).collect(Collectors.toList()));
        	return Result.ok(json);
        }
        return Result.ok(TreeUtil.buildTree(treeNodeList, MenuUtil.MENU_TOP_ID));
    }
    
    /**
     * 导出菜单管理列表
     */
    @PreAuthorize("@ss.hasPm('sys:menu:export')")
    @Log(businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public Result export(SysMenuParam param) {
    
        withOrderBy();
        List<SysMenu> list = sysMenuService.selectList(param);
        return Result.ok(DownloadUtil.exportExcel("菜单管理导出", list, SysMenu.class));
    }
    
    /**
     * 获取菜单管理详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('sys:menu:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
        return Result.ok(sysMenuService.selectById(id));
    }
    
    /**
     * 新增菜单管理
     */
    @PreAuthorize("@ss.hasPm('sys:menu:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody SysMenu sysMenu) {
    	
    	String tableUniqueCode = MenuUtil.isButton(sysMenu) ? SystemConstant.UNIQUE_MENU_BT_NAME
    			: SystemConstant.UNIQUE_MENU_NAME;
    	ValidateUtil.validUnique(sysMenu, ValidOperType.ADD, tableUniqueCode, "菜单标题已存在！");
    	
    	if(!MenuUtil.isButton(sysMenu)) {
    		ValidateUtil.validUnique(sysMenu, ValidOperType.ADD, SystemConstant.UNIQUE_MENU_PATH, "跳转路径已存在！");
    	}
    	
        return toAjax(sysMenuService.insert(MenuUtil.initMenu(sysMenu)));
    }
    
    /**
     * 修改菜单管理
     */
    @PreAuthorize("@ss.hasPm('sys:menu:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody SysMenu sysMenu) {
    
    	String tableUniqueCode = MenuUtil.isButton(sysMenu) ? SystemConstant.UNIQUE_MENU_BT_NAME
    			: SystemConstant.UNIQUE_MENU_NAME;
    	ValidateUtil.validUnique(sysMenu, ValidOperType.UPDATE, tableUniqueCode, "菜单标题已存在！");
    	
    	if(!MenuUtil.isButton(sysMenu)) {
    		ValidateUtil.validUnique(sysMenu, ValidOperType.UPDATE, SystemConstant.UNIQUE_MENU_PATH, "跳转路径已存在！");
    	}
    	
        return toAjax(sysMenuService.update(MenuUtil.initMenu(sysMenu)));
    }
    
    /**
     * 删除菜单管理
     */
    @PreAuthorize("@ss.hasPm('sys:menu:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(sysMenuService.deleteById(id));
    }
    

}
